#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <glib/gi18n.h>

#include "version.h"
#include "myapp.h"

GtkWidget *main_application_window = NULL;
userinfo gUserInfo;
guint gTimerID;
labels *gLabels;

void redrawMainWindow (labels *lbl, usageinfo *ui);
void startCheckTimer();
void stopCheckTimer();

void save_userInfo ()
{
   GKeyFile *key = g_key_file_new ();
   save_mykeys (key, &gUserInfo);
   g_key_file_free (key);
}

static void tampilProperties (GtkWidget *wid, labels *lbl)
{
  GtkWidget *label = NULL;
  GtkWidget *entry1 = NULL;
  GtkWidget *entry2 = NULL;
  GtkWidget *entry3 = NULL;
  GtkWidget *entry4 = NULL;
  //GtkWidget *entry5 = NULL;
  //GtkWidget *entry6 = NULL;
  GtkWidget *alignment = NULL;

  char *mylabels[] = {"No. Speedy :",
        "URL :",
        "Interval pemeriksaan (min.) :",
        "Batas muncul peringatan :"};
        //"Ambil alternativ jika bermasalah :",
        //"Dari URL :"};
  int i;

  stopCheckTimer ();

  GtkWidget *dialog = gtk_dialog_new_with_buttons (Q_("Properties"),
          GTK_WINDOW(main_application_window),
          GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
          GTK_STOCK_SAVE,
          GTK_RESPONSE_ACCEPT,
          GTK_STOCK_CANCEL,
          GTK_RESPONSE_REJECT,
          NULL);

  if (dialog==NULL)
  {
  	perror ("Can not create Properties dialog.");
  	exit (0);
  }

  //GtkWidget *content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));


  GtkWidget *table = gtk_table_new (4, 2, FALSE);
  //gtk_table_set_row_spacings (GTK_TABLE (table), 2);
  gtk_table_set_col_spacings (GTK_TABLE (table), 6);
  //gtk_container_add (GTK_CONTAINER (content_area), table);
  gtk_container_add (GTK_CONTAINER (GTK_DIALOG(dialog)->vbox), table);
  gtk_container_set_border_width (GTK_CONTAINER (table), 8);

  for (i=0;i<4;i++)
  {
      label = gtk_label_new (mylabels[i]);
      gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5);
      gtk_table_attach_defaults (GTK_TABLE (table), label, 0, 1, i, i+1);
  }

  entry1 = gtk_entry_new_with_max_length (15);
  gtk_entry_set_width_chars (GTK_ENTRY(entry1), 15);
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry1);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 0, 1,
    GTK_FILL, 0, 2, 2);

  entry2 = gtk_entry_new_with_max_length (255);
  gtk_entry_set_width_chars (GTK_ENTRY(entry2), 40);
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry2);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 1, 2,
    GTK_FILL, 0, 2, 2);

  entry3 = gtk_spin_button_new_with_range (0, 60, 1);
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry3);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 2, 3,
    GTK_FILL, 0, 2, 2);

  entry4 = gtk_spin_button_new_with_range (0, 100, 1);
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry4);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 3, 4,
    GTK_FILL, 0, 2, 2);

/*
  entry5 = gtk_check_button_new ();
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry5);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 4, 5,
    GTK_FILL, 0, 2, 2);

  entry6 = gtk_entry_new_with_max_length (255);
  gtk_entry_set_width_chars (GTK_ENTRY(entry6), 40);
  alignment = gtk_alignment_new (0, 0.5, 0, 0);
  gtk_container_add (GTK_CONTAINER (alignment), entry6);
  gtk_table_attach (GTK_TABLE (table), alignment, 1, 2, 5, 6,
    GTK_FILL, 0, 2, 2);
*/

  gtk_entry_set_text (GTK_ENTRY (entry1), gUserInfo.speedynumber);
  gtk_entry_set_text (GTK_ENTRY (entry2), gUserInfo.alerturl);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (entry3), gUserInfo.checkinterval);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (entry4), gUserInfo.limit2alert);
  //gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (entry5), gUserInfo.alternativ);
  //gtk_entry_set_text (GTK_ENTRY (entry6), gUserInfo.listurl);

  gtk_widget_show_all (dialog);
  gint result = gtk_dialog_run (GTK_DIALOG (dialog));
  switch (result)
  {
    case GTK_RESPONSE_ACCEPT:
       g_strlcpy (gUserInfo.speedynumber,gtk_entry_get_text(GTK_ENTRY (entry1)), 16);
       g_strlcpy (gUserInfo.alerturl,gtk_entry_get_text(GTK_ENTRY (entry2)), 128);
       gUserInfo.checkinterval = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON (entry3));
       gUserInfo.limit2alert = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON (entry4));
       //gUserInfo.alternativ = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (entry5));
       //g_strlcpy (gUserInfo.listurl,gtk_entry_get_text(GTK_ENTRY (entry6)), 128);

       save_userInfo();

       gtk_label_set_text (GTK_LABEL(lbl->lblSpeedy), gUserInfo.speedynumber);
       gtk_widget_show (lbl->lblSpeedy);
       break;
    default:
       //do_nothing_since_dialog_was_cancelled ();
       break;
   }
  gtk_widget_destroy (dialog);

  startCheckTimer ();
}

void tampilError (const char *msg)
{
    /* Show an error message */
    GtkWidget *dialog = gtk_message_dialog_new (GTK_WINDOW(main_application_window),
                                     GTK_DIALOG_MODAL,
                                     GTK_MESSAGE_ERROR,
                                     GTK_BUTTONS_CLOSE,
                                     APPNAME);
    if (msg[0])
      gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), "%s", msg);
    else
      gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
                                              "Ada masalah, tapi tidak tahu apa.");
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
}

void gagalGetData (const char *msg)
{
    if (msg[0])
      tampilError (msg);
    else
      tampilError ("Periksa seting program atau koneksi jaringan.");
}

void tampilAlert (float persen)
{
    GtkWidget *dialog;

    /* Show an error message */
    dialog = gtk_message_dialog_new (GTK_WINDOW(main_application_window),
                                     GTK_DIALOG_MODAL,
                                     GTK_MESSAGE_WARNING,
                                     GTK_BUTTONS_CLOSE,
                                     "Perhatian!");
    gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
                                              "Pemakaian Speedy Anda telah mencapai %.2f%%", persen);
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
}

void redrawMainWindow (labels *lbl, usageinfo *ui)
{
  gtk_label_set_text (GTK_LABEL(lbl->lblSpeedy), gUserInfo.speedynumber);
  gtk_widget_show (lbl->lblSpeedy);
  gtk_label_set_text (GTK_LABEL(lbl->lblQuota), ui->quota);
  gtk_widget_show (lbl->lblQuota);
  gtk_label_set_text (GTK_LABEL(lbl->lblPenggunaan), ui->penggunaan);
  gtk_widget_show (lbl->lblPenggunaan);
  // eshabe - 2009-05-27
  if (ui->penggunaan_persen>100)
  {
    gtk_label_set_text (GTK_LABEL(lbl->lblSisaTxt), "Kelebihan :");
    gtk_label_set_text (GTK_LABEL(lbl->lblSisaQuota), ui->kelebihan);
  }
  else
  {
    gtk_label_set_text (GTK_LABEL(lbl->lblSisaTxt), "Sisa :");
    gtk_label_set_text (GTK_LABEL(lbl->lblSisaQuota), ui->sisa);
  }

  // --
  gtk_widget_show (lbl->lblSisaTxt);
  gtk_widget_show (lbl->lblSisaQuota);
}

static void bacaUlangPemakaian (GtkWidget *wid, labels *lbl)
{
  usageinfo ui;
  char url[256];
  char msg[MAXMESSAGE];
  int err = 0;

  stopCheckTimer();

  memset (&gUserInfo, 0, sizeof(userinfo));
  read_mykeys (&gUserInfo);

  if (!gUserInfo.speedynumber[0])
  {
      tampilError ("Nomor Speedy belum diisi.");
      return;
  }

  strcpy (url, gUserInfo.alerturl);
  strcat (url, gUserInfo.speedynumber);
  strcat (url, "-"); // separator :P
  memset (&ui, 0, sizeof(usageinfo));
  memset (msg, 0, sizeof(msg));
  if ( getdata(url, &ui, msg) != 1 )
  {
      err = 1;
      gagalGetData(msg);
  }

  redrawMainWindow (lbl, &ui);

  if (err)
    return;

  if (ui.penggunaan_persen >= gUserInfo.limit2alert)
  {
    gtk_window_present(GTK_WINDOW(main_application_window));
    tampilAlert (ui.penggunaan_persen);
  }

  startCheckTimer();
}

gboolean OnTimerFunc ()
{
#ifdef _DEBUG
	printf ("OnTimerFunc\n");
#endif
	bacaUlangPemakaian (NULL, gLabels);
	return TRUE;
}

void startCheckTimer ()
{
	if (gUserInfo.checkinterval)
		gTimerID = g_timeout_add_seconds (gUserInfo.checkinterval*60, (GSourceFunc)OnTimerFunc, NULL);
}

void stopCheckTimer ()
{
  if (gTimerID)
    g_source_remove (gTimerID);
}

int main (int argc, char *argv[])
{
  if (argc>1 && strcmp(argv[1],"-v")==0)
  {
      printf ("\nVersion: %s\n", FULLVERSION_STRING);
      exit (0);
  }
  GtkWidget *button = NULL;
  GtkWidget *win = NULL;
  GtkWidget *hbox = NULL;
  GtkWidget *table = NULL;
  GtkWidget *label = NULL;
  labels lbl;

  char strMainWindowTitle[256];

  /* Initialize GTK+ */
  g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, (GLogFunc) gtk_false, NULL);
  gtk_init (&argc, &argv);
  g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL);

  /* Create the main window */
  sprintf (strMainWindowTitle, "%s %s", APPNAME, FULLVERSION_STRING);
  win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_resizable (GTK_WINDOW (win), FALSE);
  gtk_window_set_icon_name (GTK_WINDOW (win), GTK_STOCK_NETWORK);
  gtk_container_set_border_width (GTK_CONTAINER (win), 8);
  gtk_window_set_title (GTK_WINDOW (win), strMainWindowTitle);
  gtk_window_set_position (GTK_WINDOW (win), GTK_WIN_POS_CENTER);
  gtk_widget_realize (win);
  g_signal_connect (win, "destroy", gtk_main_quit, NULL);

  read_mykeys (&gUserInfo);
  /* Container */

  table = gtk_table_new (5, 2, FALSE);
  gtk_table_set_row_spacings (GTK_TABLE (table), 6);
  gtk_table_set_col_spacings (GTK_TABLE (table), 6);
  gtk_container_add (GTK_CONTAINER (win), table);

  label = gtk_label_new ("No. Sppedy :");
  gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), label, 0, 1, 0, 1);
  //gtk_widget_show (label);


  label = gtk_label_new ("Quota :");
  gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), label, 0, 1, 1, 2);
  //gtk_widget_show (label);

  label = gtk_label_new ("Penggunaan :");
  gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), label, 0, 1, 2, 3);
  //gtk_widget_show (label);

  // eshabe - 2009-05-27
  // label --> lbl.lblSisaTxt
  lbl.lblSisaTxt = gtk_label_new ("Sisa :");
  gtk_misc_set_alignment(GTK_MISC(lbl.lblSisaTxt), 1, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), lbl.lblSisaTxt, 0, 1, 3, 4);
  //gtk_widget_show (label);

  lbl.lblSpeedy = gtk_label_new (gUserInfo.speedynumber);
  gtk_misc_set_alignment(GTK_MISC(lbl.lblSpeedy), 0, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), lbl.lblSpeedy, 1, 2, 0, 1);
  //gtk_widget_show (lbl.lblSpeedy);

  lbl.lblQuota = gtk_label_new ("");
  gtk_misc_set_alignment(GTK_MISC(lbl.lblQuota), 0, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), lbl.lblQuota, 1, 2, 1, 2);
  //gtk_widget_show (lbl.lblQuota);

  lbl.lblPenggunaan  = gtk_label_new ("");
  gtk_misc_set_alignment(GTK_MISC(lbl.lblPenggunaan), 0, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), lbl.lblPenggunaan, 1, 2, 2, 3);
  //gtk_widget_show (lbl.lblPenggunaan);

  lbl.lblSisaQuota = gtk_label_new ("");
  gtk_misc_set_alignment(GTK_MISC(lbl.lblSisaQuota), 0, 0.5);
  gtk_table_attach_defaults (GTK_TABLE (table), lbl.lblSisaQuota, 1, 2, 3, 4);
  //gtk_widget_show (lbl.lblSisaQuota);

  hbox = gtk_hbox_new (TRUE, 6);
  gtk_table_attach_defaults (GTK_TABLE (table), hbox, 0, 2, 4, 5);

  button = gtk_button_new_from_stock (GTK_STOCK_PROPERTIES);
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (tampilProperties), (gpointer) &lbl);
  gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 0);

  button = gtk_button_new_from_stock (GTK_STOCK_REFRESH);
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (bacaUlangPemakaian), (gpointer) &lbl);
  gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 0);

  button = gtk_button_new_from_stock (GTK_STOCK_QUIT);
  g_signal_connect (button, "clicked", gtk_main_quit, NULL);
  gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 0);


  main_application_window = win;

  /* Enter the main loop */
  gtk_widget_show_all (win);

  bacaUlangPemakaian (win, &lbl);
  gLabels = &lbl;

  gtk_main ();

  stopCheckTimer ();

  return 0;
}
